#include <std.h>
#include <csl.h>
#include <csl_dat.h>
#include <csl_cache.h>
#include <chan.h>
#include <scom.h>
#include <utl.h>
#include <fvid.h>
#include <tsk.h>

#include <edc.h>
#include <vport.h>
#include <vportdis.h>
#include <saa7105.h>    

#include <evmdm642.h>                      
#include <evmdm642_disParamsSDTVDefault.h>


#include "appMain.h"
#include "appThreads.h"
#include "cap_dis_size.h"

VPORT_PortParams EVMDM642_vDisParamsPort 
  = EVMDM642_DIS_PARAMS_PORT_DEFAULT;

#if defined _NTSC

static VPORTDIS_Params EVMDM642_vDisParamsChan 
  = EVMDM642_DIS_PARAMS_CHAN_BT656_DEFAULT(NTSC);

static SAA7105_ConfParams EVMDM642_vDisParamsSAA7105 
  = EVMDM642_DIS_PARAMS_SAA7105_SDTV_DEFAULT(NTSC720, SVIDEO);

#elif defined _PAL

static VPORTDIS_Params EVMDM642_vDisParamsChan 
  = EVMDM642_DIS_PARAMS_CHAN_BT656_DEFAULT(PAL);

static SAA7105_ConfParams EVMDM642_vDisParamsSAA7105 
  = EVMDM642_DIS_PARAMS_SAA7105_SDTV_DEFAULT(PAL720, SVIDEO);
#endif

/* heap IDs defined in the BIOS configuration file */
extern int extHeap;

#pragma DATA_SECTION(scratch2,".internal_data1");
#pragma DATA_ALIGN(scratch2,8);
unsigned char scratch2[20*LINE_SZ];

//extern unsigned char scratch1[];

FVID_Handle  disChan;
FVID_Frame *disFrameBuf;

void tskVideoOutputInit()
{

    int             status;

    EVMDM642_vDisParamsChan.segId = extHeap;

    EVMDM642_vDisParamsSAA7105.hI2C = EVMDM642_I2C_hI2C;

    disChan = FVID_create("/VP2DISPLAY", IOM_OUTPUT,
        &status, (Ptr)&EVMDM642_vDisParamsChan, NULL);

    FVID_control(disChan, VPORT_CMD_EDC_BASE+EDC_CONFIG, (Ptr)&EVMDM642_vDisParamsSAA7105);

}

void tskVideoOutputStart()
{
}
/* handle video capture, scaling and re-format */


void tskVideoOutput()
{
    char *inBuf[3], *outBuf[3];
    SCOM_Handle fromProctoOut,fromOuttoProc;
    ScomMessage scomMsg;
    ScomMessage *pMsgBuf;

    fromProctoOut = SCOM_open("PROCTOOUT");
    fromOuttoProc = SCOM_open("OUTTOPROC");

    FVID_control(disChan, VPORT_CMD_START, NULL);

    FVID_alloc(disChan, &disFrameBuf);

    // Give the process thread a buffer to pass back to us
    SCOM_putMsg(fromOuttoProc, &scomMsg);

    while(1)
    {
        pMsgBuf = SCOM_getMsg(fromProctoOut, SYS_FOREVER);

        UTL_stsStart( stsDispTime );

        inBuf[0] = pMsgBuf->bufY;
        inBuf[1] = pMsgBuf->bufU;
        inBuf[2] = pMsgBuf->bufV;

        outBuf[0] =  disFrameBuf->frame.iFrm.y1;
        outBuf[1] =  disFrameBuf->frame.iFrm.cb1;
        outBuf[2] =  disFrameBuf->frame.iFrm.cr1;

        yuv420to422(inBuf,outBuf,LINE_SZ,NUM_LINES);

        UTL_stsStop( stsDispTime );

        SCOM_putMsg(fromOuttoProc, pMsgBuf);

        FVID_exchange(disChan, &disFrameBuf);
    }
}

